﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Data;
using System.Data.Objects;

using LIM.model;

namespace LIM.controller
{
    public class BaseController
    {
        protected LIMS_Entities LIMS_Entities = new LIMS_Entities();
        //protected LIMS_Entities LIMS_Entities = new LIMS_Entities(LIMS_EntityConnection.Create_LIMS_EntityConnection());
                
        public virtual bool SaveObject(object entity, out string pMessage, out int Code)
        {            
            bool returnValue = false;
            pMessage = string.Empty;
            PropertyInfo pro = entity.GetType().GetProperty("RowID");
            try
            {
                if (int.Parse(pro.GetValue(entity, null).ToString()) == 0)
                {
                    LIMS_Entities.AddObject(entity.GetType().Name, entity);
                }
                LIMS_Entities.SaveChanges();
                LIMS_Entities.Refresh(RefreshMode.StoreWins, entity);

                returnValue = true;
            }
            catch (Exception ex)
            {
                //LogService.WriteLog((int)LogLevel.INFO, ex.StackTrace);
                //LogService.WriteLog((int)LogLevel.ERROR, ex.Message);
                pMessage = ex.Message;
            }
            //pMessage = Message;
            Code = int.Parse(pro.GetValue(entity, null).ToString());
            return returnValue;
        }

        public virtual bool DeleteObject(object entity, out string pMessage)
        {
            bool returnValue = false;
            string Message = string.Empty;
            try
            {
                LIMS_Entities.DeleteObject(entity);
                LIMS_Entities.SaveChanges();
                returnValue = true;
            }
            catch (Exception ex)
            {
                //LogService.WriteLog((int)LogLevel.INFO, ex.StackTrace);
                //LogService.WriteLog((int)LogLevel.ERROR, ex.Message);
                Message = ex.Message;
            }
            pMessage = Message;
            return returnValue;
        }

        public virtual object GetObjectByCode(Type objType, int pCode)
        {
            EntityKey key = new EntityKey(LIMS_Entities.DefaultContainerName + "." + objType.Name, "RowID", pCode);
            return LIMS_Entities.GetObjectByKey(key);
        }

        public virtual DateTime GetCurrentDateTimeFromDatabaseServer()
        {
            var dQuery = LIMS_Entities.CreateQuery<DateTime>("CurrentDateTime()");
            return dQuery.AsEnumerable().First();
        }

    }
}
